﻿using Furion;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using BaseNet.Application.System.Upload.Dto;
using BaseNet.Core.Consts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ImageMagick;
using Furion.FriendlyException;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;

namespace BaseNet.Application.System.Upload
{
    [ApiDescriptionSettings(Module = ModuleConsts.System)]
    [SecurityDefine(SecurityConsts.System_Upload)]
    public class UploadService : IDynamicApiController
    {
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<UploadOutput> UploadFile([FromForm(Name = "file")] IFormFile file)
        {
            var result = new UploadOutput();

            var suffix = Path.GetExtension(file.FileName).ToLower().Replace(".", "");//文件后缀
            var relativePath = "/uploads/" + suffix + "/" + DateTime.Now.ToString("yyyyMM");//相对路径
            var fileName = Guid.NewGuid().ToString("N") + "." + suffix;//图片重命名

            var absolutePath = App.HostEnvironment.ContentRootPath + relativePath;//绝对路径

            if (!Directory.Exists(absolutePath))
            {
                Directory.CreateDirectory(absolutePath);
            }

            if (IsImg(suffix))//图片上传进行图片压缩
            {
                //使用Magick.NET.Core开源类库进行图片压缩
                //压缩最小360像素宽度，25%的画质，尽量缩小图片大小
                using (var image = new MagickImage(file.OpenReadStream()))
                {
                    var radio = image.Width > 360 ? Math.Round(image.Width / 360d, 2) : 1;//缩放比例，将缩略图片宽度设置为最低360
                    image.Resize((int)Math.Round(image.Width / radio), (int)Math.Round(image.Height / radio));
                    image.Write(Path.Combine(absolutePath, fileName));
                }
            }
            else//文件上传使用原文件上传方式
            {
                using (var stream = File.Create(Path.Combine(absolutePath, fileName)))//在指定路径中创建或覆盖文件。
                {
                    await file.CopyToAsync(stream);
                }
            }

            result.Path = relativePath + "/" + fileName;//将相对路径+文件名返回去
            result.FileName = fileName;//返回文件名
            result.Suffix = suffix;//文件后缀
            return result;
        }

        /// <summary>
        /// 图片判断
        /// </summary>
        /// <param name="suffix"></param>
        /// <returns></returns>
        private bool IsImg(string suffix)
        {
            List<string> imgSuffix = new List<string> { "png", "jpg", "jpeg", "gif" };
            return imgSuffix.Any(o => o.Contains(suffix));
        }
    }
}
